/**
 * 用户状态管理
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, LoginParams, RegisterParams } from '@/types/user'
import { checkIn, logout, getCurrentUser } from '@/api/user'
import { getUserProfile } from '@/api/account'

// Token存储键名
const TOKEN_KEY = 'user_token'
const REFRESH_TOKEN_KEY = 'user_refresh_token'
const USER_INFO_KEY = 'user_info'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(localStorage.getItem(TOKEN_KEY) || '')
  const refreshToken = ref<string>(localStorage.getItem(REFRESH_TOKEN_KEY) || '')
  const userInfo = ref<User | null>(null)
  const isLoading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  const userId = computed(() => userInfo.value?.id)
  const username = computed(() => userInfo.value?.username)
  const nickname = computed(() => userInfo.value?.nickname || userInfo.value?.username)
  const avatar = computed(() => userInfo.value?.avatar)
  const email = computed(() => userInfo.value?.email)
  const mobile = computed(() => userInfo.value?.mobile)

  /**
   * 设置Token
   */
  const setToken = (newToken: string, newRefreshToken?: string) => {
    token.value = newToken
    localStorage.setItem(TOKEN_KEY, newToken)
    
    if (newRefreshToken) {
      refreshToken.value = newRefreshToken
      localStorage.setItem(REFRESH_TOKEN_KEY, newRefreshToken)
    }
  }

  /**
   * 设置用户信息
   */
  const setUserInfo = (info: User) => {
    userInfo.value = info
    localStorage.setItem(USER_INFO_KEY, JSON.stringify(info))
  }

  /**
   * 清除用户数据
   */
  const clearUserData = () => {
    token.value = ''
    refreshToken.value = ''
    userInfo.value = null
    localStorage.removeItem(TOKEN_KEY)
    localStorage.removeItem(REFRESH_TOKEN_KEY)
    localStorage.removeItem(USER_INFO_KEY)
  }

  /**
   * 从本地存储恢复用户信息
   */
  const restoreUserInfo = () => {
    const storedUserInfo = localStorage.getItem(USER_INFO_KEY)
    if (storedUserInfo) {
      try {
        userInfo.value = JSON.parse(storedUserInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        localStorage.removeItem(USER_INFO_KEY)
      }
    }
  }

  /**
   * 用户登录
   */
  const login = async (params: LoginParams) => {
    try {
      isLoading.value = true
      const response = await checkIn(params)

      console.log('登录API响应:', response)

      if (response.code === 1) {
        const responseData = response.data
        console.log('登录响应数据结构:', responseData)

        // 提取用户信息
        let user: User | null = null
        if (responseData.userInfo) {
          user = responseData.userInfo
        } else if (responseData.user) {
          user = responseData.user
        } else if (responseData.id && responseData.username) {
          // 如果响应数据本身包含用户字段，将其作为用户信息
          console.warn('未找到标准用户信息字段，使用响应数据作为用户信息')
          user = responseData as User
        }

        if (user && user.id) {
          // 保存用户信息
          setUserInfo(user)
          console.log('保存用户信息成功:', user)

          // 处理token
          let tokenValue = null
          if (responseData.token) {
            tokenValue = responseData.token
          } else if ((user as any).token) {
            tokenValue = (user as any).token
          }

          if (tokenValue) {
            setToken(tokenValue, responseData.refreshToken)
            console.log('保存token成功:', tokenValue)
          } else {
            // 生成临时token以标识登录状态（依赖session/cookie认证）
            const tempToken = `session_${Date.now()}_${user.id}`
            setToken(tempToken)
            console.log('生成临时token:', tempToken)
          }

          return responseData
        } else {
          throw new Error('用户信息格式错误')
        }
      } else {
        throw new Error(response.message || response.msg || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 用户注册
   */
  const register = async (params: RegisterParams) => {
    try {
      isLoading.value = true
      const response = await checkIn(params)

      if (response.code === 1) {
        const responseData = response.data
        console.log('注册响应数据结构:', responseData)

        // 提取用户信息
        let user: User | null = null
        if (responseData.userInfo) {
          user = responseData.userInfo
        } else if (responseData.user) {
          user = responseData.user
        } else if (responseData.id && responseData.username) {
          user = responseData as User
        }

        if (user && user.id) {
          // 保存用户信息
          setUserInfo(user)
          console.log('保存用户信息成功:', user)

          // 处理token
          let tokenValue = null
          if (responseData.token) {
            tokenValue = responseData.token
          } else if ((user as any).token) {
            tokenValue = (user as any).token
          }

          if (tokenValue) {
            setToken(tokenValue, responseData.refreshToken)
            console.log('保存token成功:', tokenValue)
          } else {
            // 生成临时token以标识登录状态
            const tempToken = `session_${Date.now()}_${user.id}`
            setToken(tempToken)
            console.log('生成临时token:', tempToken)
          }

          return responseData
        } else {
          throw new Error('用户信息格式错误')
        }
      } else {
        throw new Error(response.message || '注册失败')
      }
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 用户登出
   */
  const logoutUser = async () => {
    try {
      isLoading.value = true
      await logout(refreshToken.value)
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      clearUserData()
      isLoading.value = false
    }
  }

  /**
   * 获取当前用户信息
   */
  const fetchUserInfo = async () => {
    try {
      const response = await getCurrentUser()
      if (response.code === 1) {
        setUserInfo(response.data)
        return response.data
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，可能是token过期，清除本地数据
      clearUserData()
      throw error
    }
  }

  /**
   * 更新用户信息
   */
  const updateUserInfo = (updates: Partial<User>) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...updates }
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo.value))
    }
  }

  /**
   * 初始化用户状态
   */
  const initializeUser = async () => {
    // 恢复本地存储的用户信息
    restoreUserInfo()

    // 如果有token但没有用户信息，尝试获取用户信息
    if (token.value && !userInfo.value) {
      try {
        await fetchUserInfo()
      } catch (error) {
        // 获取失败，清除token
        console.warn('获取用户信息失败，清除本地数据:', error)
        clearUserData()
      }
    }

    // 如果有用户信息但没有token，可能是session认证，生成临时token
    if (!token.value && userInfo.value) {
      const tempToken = `session_${Date.now()}_${userInfo.value.id}`
      setToken(tempToken)
    }
  }

  return {
    // 状态
    token: computed(() => token.value),
    refreshToken: computed(() => refreshToken.value),
    userInfo: computed(() => userInfo.value),
    isLoading: computed(() => isLoading.value),
    
    // 计算属性
    isLoggedIn,
    userId,
    username,
    nickname,
    avatar,
    email,
    mobile,
    
    // 方法
    setToken,
    setUserInfo,
    clearUserData,
    login,
    register,
    logout: logoutUser,
    fetchUserInfo,
    updateUserInfo,
    initializeUser
  }
})
